import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

//html转图片  不支持promise.all
const htmlstrToImg = async (
  htmlStr: string,
  imgWidth: number, //图片宽度
  imgHeight: number //图片高度，传0自适应
) => {
  const boxEle = document.createElement('div');
  boxEle.style['overflow'] = 'hidden';
  boxEle.style['height'] = '0px';
  const element = document.createElement('div');
  element.innerHTML = htmlStr;
  if (imgWidth) element.style.width = imgWidth + 'px';
  if (imgHeight) element.style.height = imgHeight + 'px';
  element.style.wordWrap = 'break-word';
  boxEle.appendChild(element);

  document.body.appendChild(boxEle);
  const canvas = await html2canvas(element, {
    width: imgWidth,
    height: element.clientHeight,
    scale: 4
  });
  const url = canvas.toDataURL();
  document.body.removeChild(boxEle);
  return Promise.resolve(url);
};

//加载图片对象
const loadImage = (path: string): Promise<HTMLImageElement> => {
  return new Promise((reject, resolve) => {
    const imgage = new Image();
    imgage.src = path;
    imgage.onload = function () {
      reject(imgage);
    };
  });
};

//图片批量转pdf
const ImgListToPdf = async (
  imgList: string[],
  pageWidth: number, //每页宽度px
  pageHeight: number, //每页高度px
  pageMargins: number //页边距
) => {
  const pdf = new jsPDF({
    format: [pageWidth, pageHeight],
    orientation: pageWidth < pageHeight ? 'p' : 'l',
    unit: 'px',
    hotfixes: ['px_scaling']
  });
  const proportion =
    (pageHeight - pageMargins * 2) / (pageWidth - pageMargins * 2);
  //图片超长做裁切
  for (let i1 = 0; i1 < imgList.length; i1++) {
    const imageEle = await loadImage(imgList[i1]);
    const imgWidth = imageEle.width;
    const imgHeight = imageEle.width * proportion;
    const imgNum = imageEle.height / imgHeight;
    for (let i2 = 0; i2 < imgNum; i2++) {
      if (i1 || i2) pdf.addPage();
      let myCanvas: any = document.createElement('canvas');
      myCanvas.width = pageWidth - pageMargins * 2;
      myCanvas.height = pageHeight - pageMargins * 2;
      const ctx = myCanvas.getContext('2d');
      ctx?.drawImage(
        imageEle,
        0,
        i2 * imgHeight,
        imgWidth,
        imgHeight,
        0,
        0,
        myCanvas.width,
        myCanvas.height
      );
      pdf.addImage({
        imageData: myCanvas.toDataURL(),
        format: 'PNG',
        x: pageMargins,
        y: pageMargins,
        width: myCanvas.width,
        height: myCanvas.height
      });
      myCanvas = undefined;
    }
  }
  return pdf.output('blob');
};

//html字符转pdf  不支持promise.all
export const htmlStrToPdf = async (
  htmlStrlist: string[],
  pageWidth: number, //每页宽度px
  pageHeight: number, //每页长度px
  pageMargins: number //页边距px
) => {
  const imgList = [];
  for (let i = 0; i < htmlStrlist.length; i++) {
    imgList.push(
      await htmlstrToImg(
        htmlStrlist[i] || '<div style="height: 20px"></div>',
        pageWidth - pageMargins * 2,
        0
      )
    );
  }
  const pdf = ImgListToPdf(imgList, pageWidth, pageHeight, pageMargins);
  return Promise.resolve(pdf);
};

//存放常用尺寸
export const paper = {
  a4: {
    width: 750,
    height: 1060
  }
};
